<?php  
class Model_Review extends Model{  

  public function add($userid,$postid,$content,$images){
     
    Database::instance()->begin();

      list($insert_id, $total_rows)= DB::insert('review')

      ->columns(array('postid','userid','content','images','createdon'))

      ->values(array($postid,$userid,$content,$images,date("Y-m-d h:i:sa")))

      ->execute();

      DB::update("post")->set(array('review' =>DB::expr("review+1")))->where( 'postid','=',$postid)->execute();

      Database::instance()->commit();

      $result=array();

      $user=Session::instance()->get('user');

      $result['data']=array(
        'id'=>$insert_id,
        'fullname'=>$user['username'],
        'photo'=>$user['photo'],
        'content'=>$content,
        'time'=>date("Y-m-d h:i:sa"),
        'parentid'=>'0'
      );

      $result['code']="0x00000";

      return $result;

  }

  public function reply($userid,$postid,$review_id,$parent_id,$content){
     
    Database::instance()->begin();

      list($insert_id, $total_rows)= DB::insert('review')

      ->columns(array('postid','userid','c_review','parentid','content','createdon'))

      ->values(array($postid,$userid,$review_id,$parent_id,$content,date("Y-m-d h:i:sa")))

      ->execute();

      $model_message=new Model_Message();

      $model_message->generate($userid,$postid,'review');

      Database::instance()->commit();

      $result=array();

      $user=Session::instance()->get('user');

      $result['data']=array(
        'id'=>$insert_id,
        'fullname'=>$user['username'],
        'photo'=>$user['photo'],
        'content'=>$content,
        'time'=>date("Y-m-d h:i:sa")
      );

      $result['code']="0x00000";

      return $result;

  }

  public function getInfo($postid,$offset=0,$rows=20){

      $total= DB::select(array(DB::expr('count(1)'), 'total'))

      ->from('review')->where("postid",'=',$postid)

      ->and_where("parentid",'=','0')

      ->execute()->get("total");

      $sql="select t.reviewid id,t.userid,s.fullname,s.photo,t.content,t.images,t.parentid,t.c_review review_id,t.createdon time
           from review t
           left join site_user s on s.site_userid=t.userid
           where t.postid='$postid'
           and parentid='0'
           order by t.CreatedOn desc
           limit $offset,$rows";

      $data=DB::query(Database::SELECT,$sql)->execute()->as_array();

      return array("total"=>$total,"list"=>$data);

  }

  public function getReplyInfo($postid,$review_id){

      $sql="select t.reviewid id,t.userid,s.fullname,s.photo,t.content,t.images,t.parentid,t.c_review review_id,t.createdon time
           from review t
           left join site_user s on s.site_userid=t.userid
           where t.postid='$postid'
           and t.c_review='$review_id'
           order by t.CreatedOn";

      $data=DB::query(Database::SELECT,$sql)->execute()->as_array();

      return $data;

  }

}
